<template>
    <section class="oragin_info_form" >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="组织名称" prop="name">
                <el-input v-model="form.name" size="small" style="width: 380px;" v-if="type==='add'" ></el-input>
                <el-input v-model="form.name" size="small" style="width: 380px;" v-if="type==='update'"></el-input>
                <span v-if="type==='detail'">{{this.form.name}}</span>
            </el-form-item>
            <el-form-item label="组织标识">
                <el-input  style="width: 180px;" size="small" placeholder="由系统自动生成" disabled v-if="type==='add'"></el-input>
                <el-input  style="width: 180px;" size="small" v-model="form.code" disabled v-if="type==='update'"></el-input>
                <span v-if="type==='detail'">{{this.form.code}}</span>
            </el-form-item>

            <el-form-item label="状态">
                <el-radio-group v-model="form.radioState" size="small" v-if="type==='add'">
                    <el-radio-button :label="1" >启用</el-radio-button>
                    <el-radio-button :label="0" >禁用</el-radio-button>
                </el-radio-group>
            <el-radio-group v-model="form.radioState" size="small" v-if="type==='update'" >
                <el-radio-button :label="1" >启用</el-radio-button>
                <el-radio-button :label="0" >禁用</el-radio-button>
            </el-radio-group>
                <span v-if="type==='detail'">{{this.form.state ? '是' : '否'}}</span>
            </el-form-item>

            <el-form-item label="类型">
                <el-checkbox-group v-model="form.checkList" :min="1" v-if="type==='add'">
                    <el-checkbox :label="1" name="type"  style="display: block;">请求方</el-checkbox>
                    <el-form-item label-width="100px" prop="checkListQuyu" label="所属区域" v-if="quyuDisplay">
                        <el-radio-group v-model="form.checkListQuyu" size="mini">
                            <el-radio-button
                                v-for="quyu in checkListQuyuList" 
                                :label="quyu.id" 
                                :key="quyu.id"
                                name="checkListQuyu">
                                {{quyu.name}} &nbsp
                            </el-radio-button> 
                        </el-radio-group>                 
                    </el-form-item>
                    <div style="margin-top: 20px">
                        <el-form-item label-width="100px"
                            v-if="quyuDisplay"
                            v-model="form.input1"
                            size = "small"
                            :label="'请求IP地址'+(Number(index)+1)"
                            v-for="(item,index) in form.input1"
                            :prop="'input1.' + index + '.adress'"
                            :rules="[
                                {
                                    required: true, message: 'IP地址不能为空', trigger: 'blur'
                                },
                                {
                                    pattern: /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/, message: '请输入有效的IP地址' 
                                }
                            ]"
                            style="margin-bottom: 20px;"
                        >
                            <el-input v-model="item.adress" style="width: 280px;"></el-input>
                            <i @click="addIp" class="el-icon-circle-plus-outline" v-if="index===form.input1.length-1"></i>
                            <i @click="delIp(index)" class="el-icon-circle-close-outline" 
                                v-if="index!=form.input1.length-1">
                            </i>
                        </el-form-item>
                    </div>
                    <el-checkbox :label="0" name="type" style="display: block;">服务方</el-checkbox>
                    <div class=""  >
                        <el-form-item label-width="100px"
                            v-if="producerTypeSelectDispaly"
                            v-model = "form.input2"
                            size = "small"
                            v-for="(item,index) in form.input2"
                            :label="'联系人'+(Number(index)+1)"
                            :prop="'input2.' + index + '.phone'"
                            :rules="[
                                {
                                    required: true, message: '手机号不能为空', trigger: 'blur'
                                },
                                {
                                    pattern: /^1[34578]\d{9}$/, message: '请输入正确的手机号码' 
                                }
                            ]"
                            style="margin-bottom: 15px;"
                        >
                            <el-input v-model="item.name" size="small" style="width: 80px;"></el-input>
                            <span>
                                电话{{Number(index)+1}}
                            </span>
                            <el-input v-model="item.phone" size="small" style="width: 180px;"></el-input>
                            <i @click="addPhone" class="el-icon-circle-plus-outline" 
                                v-if="index===form.input2.length-1">
                            </i>
                            <i @click="delPhone(index)" class="el-icon-circle-close-outline" 
                                v-if="index!=form.input2.length-1">
                            </i>
                        </el-form-item>
                    </div>
                </el-checkbox-group>
              <el-checkbox-group v-model="form.checkList" :min="1" v-if="type==='update'">
                    <el-checkbox :label="1" name="type"  style="display: block;">请求方</el-checkbox>
                    <el-form-item label-width="100px" prop="checkListQuyu" label="所属区域" v-if="quyuDisplay">
                        <el-radio-group v-model="form.checkListQuyu" size="mini">
                            <el-radio-button
                                v-for="quyu in checkListQuyuList" 
                                :label="quyu.id" 
                                :key="quyu.id"
                                name="checkListQuyu">
                                {{quyu.name}} &nbsp
                            </el-radio-button> 
                        </el-radio-group>                 
                    </el-form-item>
                    <div style="margin-top: 20px">
                        <el-form-item label-width="100px"
                            v-if="quyuDisplay"
                            v-model="form.input1"
                            size = "small"
                            :label="'请求IP地址'+(Number(index)+1)"
                            v-for="(item,index) in form.input1"
                            :prop="'input1.' + index + '.adress'"
                            :rules="[
                                {
                                    required: true, message: 'IP地址不能为空', trigger: 'blur'
                                },
                                {
                                    pattern: /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/, message: '请输入有效的IP地址' 
                                }
                            ]"
                            style="margin-bottom: 20px;"
                        >
                            <el-input v-model="item.adress" style="width: 280px;"></el-input>
                            <i @click="addIp" class="el-icon-circle-plus-outline" v-if="index===form.input1.length-1"></i>
                            <i @click="delIp(index)" class="el-icon-circle-close-outline" 
                                v-if="index!=form.input1.length-1">
                            </i>
                        </el-form-item>
                    </div>
                    <el-checkbox :label="0" name="type" style="display: block;">服务方</el-checkbox>
                    <div class=""  >
                        <el-form-item label-width="100px"
                            v-if="producerTypeSelectDispaly"
                            v-model = "form.input2"
                            size = "small"
                            v-for="(item,index) in form.input2"
                            :label="'联系人'+(Number(index)+1)"
                            :prop="'input2.' + index + '.phone'"
                            :rules="[
                                {
                                    required: true, message: '手机号不能为空', trigger: 'blur'
                                },
                                {
                                    pattern: /^1[34578]\d{9}$/, message: '请输入正确的手机号码' 
                                }
                            ]"
                            style="margin-bottom: 15px;"
                        >
                            <el-input v-model="item.name" size="small" style="width: 80px;"></el-input>
                            <span>
                                电话{{Number(index)+1}}
                            </span>
                            <el-input v-model="item.phone" size="small" style="width: 180px;"></el-input>
                            <i @click="addPhone" class="el-icon-circle-plus-outline" 
                                v-if="index===form.input2.length-1">
                            </i>
                            <i @click="delPhone(index)" class="el-icon-circle-close-outline" 
                                v-if="index!=form.input2.length-1">
                            </i>
                        </el-form-item>
                    </div>
              </el-checkbox-group>
              <span v-if="type==='detail'">{{this.form.type}}</span>
            </el-form-item>
      <div class="fixed_button">      
          <el-form-item v-if="type==='add'">
            <el-button @click="disappears">取消</el-button>
            <el-button type="primary" @click="onSubmit('form')">确定</el-button>
          </el-form-item>
          <el-form-item v-if="type==='update'">
            <el-button @click="disappears">取消</el-button>
            <el-button type="primary" @click="onSubmitUpdata('form')">确定</el-button>
          </el-form-item>
      </div>
    </el-form>
    </section>
</template>

<script>
    import {organizationDataExchangeListDetail,
            organizationDataExchangeAdd,
            organizationDataExchangeUpdata,
            organizationDataExchangeListSearch,
            organizationDataExchangeQuyu,
    } from '../../api/data-exchange-api.js'

    export default {
        props:{
            type: {     //显示add,update,detail的值
                type: String,
                default: 'auto'
            },
            objDetail: Object,  //具体对象详细内容
            content: '',
            objid: {
                type: Number,
                default: 12
            },
            organization: Object
        },
        data() {
            return {
                form: {
                    name: '',   //组织名称
                    code: '',   //编码
                    type: '',   //详情类型
                    state: '',    //详情状态
                    radioState:"1",    //状态
                    checkList:[1,],   //请求方，服务方选择
                    checkListQuyu: '',    //所属区域
                    input1:[
                        {
                          adress:''    //请求方IP地址
                        }
                    ],
                    input2:[
                        {
                          name:'',    //联系人名称
                          phone:'',    //联系人手机
                        }
                    ],
                },
                rules: {
                    name:[
                        { required: true, message: '请输入组织信息名称', trigger: 'blur' },
                        { min: 3, max: 20, message: '长度在 3 到 20个字符', trigger: 'blur' }
                    ],
                    checkListQuyu: [
                        {  required: true, message: '请至少选择一个区域', trigger: 'change' }
                    ],
                },
                ips: '',    //添加的IP地址
                contacts: '',    //添加的联系方式
                checkListQuyuList: [],    //查询所属区域列表
                selectcheckListQuyu: '',    //选择打钗的区域
                quyuDisplay: true,  //是否显示选择区域
                producerTypeSelectDispaly: false,   //是否显示填写联系人
                requesterType: '',  //选择请求方
                producerType: '',   //选择服务方
            }
        },
        methods: {
            onSubmit(formName) {    //提交新增组织
                this.countIps();
                this.countContacts();
                this.$refs[formName].validate((valid) => {
                  if (valid) {
                    organizationDataExchangeAdd({   //新增组织信息
                        requesterType: this.requesterType,   //请求方固定了值是1，如果它是请求方就写1，如果不是请求方传空值
                        nodeIds:  this.selectcheckListQuyu, //'90，9，'     //区域选择
                        name: this.form.name,       
                        producerType: this.producerType ,    //服务方，固定了值是1，如果它是服务方就写1，如果不是服务方传空值
                        status: this.form.radioState ,      //状态
                        ips: this.ips ,
                        contacts: this.contacts 
                        }).then(res => {
                            console.log(res);
                            this.listSearch();
                        }).catch(error =>{
                            console.log(error);
                    });
                    this.disappears();
                    //清空输入框数据
                    this.clearEntry();
//                  alert('成功新增组织信息');
                    this.$message.success('成功新增组织信息')
                    this.$emit('listSearch');
                  } else {
//                  console.log('error submit!!');
                    this.$message.error('error submit!')
                    return false;
                  }
                });
                
            },
            onSubmitUpdata(formName){     //组织信息更新
                this.countIps();
                this.countContacts();
                this.$refs[formName].validate((valid) => {
                  if (valid) {
                        organizationDataExchangeUpdata({
                            id: this.objid,    //必须要传id
                            requesterType: this.requesterType,   //请求方
                            producerType: this.producerType,    //服务方
                            nodeIds:  this.selectcheckListQuyu ,      //'90，9，'     //区域选择
                            name: this.form.name,
                            status: this.form.radioState,   //状态
                            ips: this.ips,
                            contacts: this.contacts
                        }).then(res => {
                            console.log(res);
                            this.listSearch();
                            this.objid = 0;
                        }).catch(error =>{
                            console.log(error);
                        })
                        this.disappears();
                        //清空输入框数据
                        this.clearEntry();
                        
//                      alert('组织信息更新成功!');
                        this.$message.success('组织信息更新成功!')
                           this.$emit('listSearch');
                  } else {
//                  console.log('error submit!!');
                    this.$message.error('error submit!!')
                    return false;
                  }
                });
                
            },
            listSearch(){   
                organizationDataExchangeListSearch(this.organization).then(res => {
                    const result = res.data.data.list;
                    console.log(res.data.data);
                    const tableData = [];
                    for(let i=0 ; i < result.length; i++ ){
                        let obj = {};
                        let resultType = '';
                        let resultState = '';
                        if(result[i].producerType == 1 && result[i].requesterType == 1){
                            resultType = '服务方/请求方'
                        }else if(result[i].requesterType == 1){
                            resultType = '请求方'
                        }else if(result[i].producerType == 1){
                            resultType = '服务方'
                        }
                        resultState = result[i].status ? '是' : '否';
                        obj.code = result[i].id;
                        obj.oragion = result[i].name;
                        obj.type = resultType;
                        obj.state = resultState;
                        tableData.push(obj);
                        // console.log(obj);
                        this.$emit('tableDataSub',tableData)
                    }
                }).catch(error => {
                    console.log(error);
                })
            },
            addIp(){/*请求IP地址增加*/
                this.form.input1.push({address:''});
                console.log(this.form.input1);
            },
            addPhone(){    //添加服务方联系方式
                this.form.input2.push({name:'',phone:''});
            },
            delPhone(index){
                this.form.input2.splice(index,1);
            },
            delIp(index){
                this.form.input1.splice(index,1);
            },
            disappears(){
                this.$emit('disappear', false);
            },
            listDetail(param){
                organizationDataExchangeListDetail({},param).then( res => {   //组织信息列表详细内容
                    const forms = res.data.data
                    console.log(forms);
                    this.form.name = forms.name
                    this.form.code = forms.id
                    this.form.type = forms.producerType
                    this.form.state = forms.status
                    this.form.checkListQuyu = forms.nodeIds;
                    let ipss = forms.ips.split(',');
                    this.form.input1 = [];
                    for(let i=0; i<ipss.length; i++){
                        this.form.input1.push({adress:ipss[i]});
                    }
                    let contactss = forms.contacts.split(';');
                    this.form.input2 = [];
                    for(let i=0; i<contactss.length-1; i++){
                        this.form.input2.push({name:contactss[i].split(',')[0],phone:contactss[i].split(',')[1]});
                    }
                    if(forms.producerType==1 && forms.requesterType==1){
                        this.form.checkList = [1,0];
                        this.quyuDisplay = true;
                        this.producerTypeSelectDispaly = true;
                        return;
                    }else if(forms.requesterType==1){
                        this.form.checkList = [1,];
                        this.quyuDisplay = true;
                        return;
                    }else if(forms.producerType==1){
                        this.quyuDisplay = false;
                        this.form.checkList = [,0];
                        this.producerTypeSelectDispaly = true;
                        return;
                    }
                    
                }).catch(error => {
                    console.log(error)
                });
            },
            listSearchQuyu(){   //查询区域数据
                organizationDataExchangeQuyu({}).then(res =>{
                    this.checkListQuyuList = res.data.data.list;
                    // console.log(res); 
                }).catch(error =>{
                    console.log(error);
                });
            },
            formTypeChange(){   //类型更新
                setTimeout(()=>{
                    if(this.requesterType == 1 && this.producerType==1){
                        this.form.type = '服务方/请求方'
                    }else if(this.requesterType == 1){
                        this.form.type = '请求方'
                    }else if(this.producerType==1){
                        this.form.type = '服务方'
                    }
                },100);
            },
            countIps(){   //计算ips的值
                let result;
                let newAddress = this.form.input1;
                for(let i = 0; i < newAddress.length; i++){
                    if(newAddress[i].adress != undefined){
                        result += newAddress[i].adress+','
                        let end = result.slice(9);
                        this.ips = end;
                        console.log(this.ips);
                    }
                }
            },
            countContacts(){    //计算contacts的值
                let result;
                let newName = this.form.input2
                for(let i = 0; i < newName.length; i++){
                    result += newName[i].name + ',' + newName[i].phone +';'
                    let end = result.slice(9);
                    this.contacts = end;
                    console.log(this.contacts);
                }
            },
            clearEntry(){   //清空输入框数据
                this.form = {
                    name: '',   //组织名称
                    code: '',   //编码
                    type: '',   //详情类型
                    state: '',    //详情状态
                    radioState:"1",    //状态
                    checkList:[1,],   //请求方，服务方选择
                    checkListQuyu: '',    //所属区域
                    input1:[
                        {
                          adress:''    //请求方IP地址
                        }
                    ],
                    input2:[
                        {
                          name:'',    //联系人名称
                          phone:'',    //联系人手机
                        }
                    ],
                };
            }
        },
        watch: {
            objid: function(newval,oldval) {
                //解决详细内容第一次不更新问题
                if(newval == 0){
                    this.listDetail(oldval);
                    this.formTypeChange();
                }else{
                    this.listDetail(newval);
                    this.formTypeChange();
                }
            },
            type: function(newVal,oldval){    //新增组织时，名称输入框里清空
                if(newVal== 'add'){
                    //清空输入框数据
                    this.clearEntry();
                    console.log('新增组织时，名称输入框里清空new')
                }else if( newVal == 'update'){
                    this.listDetail(this.objid);
                }
                console.log('gogogo')
            },
            'form.checkListQuyu': { //选择区域方法
                handler(newval, oldval){
                    console.log(newval.toString());
                    this.selectcheckListQuyu = newval.toString();
                },
                immediate: true,
            },
            'form.checkList': {
                handler(newName, oldName) {     //请求方与服务方的选择处理
                    console.log(newName);
                    if(newName.length == 1){
                        if(newName[0] == 1){
                            this.requesterType = 1;
                            this.producerType = ''
                        }else{
                            this.requesterType = '';
                            this.producerType = 1
                        }
                    }else{
                        this.requesterType = 1;
                        this.producerType = 1
                    }

                    if(this.requesterType == ''){
                        this.quyuDisplay = false;   //不显示区域选择
                        this.selectcheckListQuyu = ''   //清空所有选择区域
                    }else{
                        this.quyuDisplay = true;
                    }

                    if(this.producerType == ''){
                        this.producerTypeSelectDispaly = false;   //不显示填写联系人
                    }else{
                        this.producerTypeSelectDispaly = true;
                    }
                    console.log(this.requesterType);
                    console.log(this.producerType);

                },
                immediate: true,
            },
            'form.input2': {
                handler(newName, oldName){
                    //计算contacts的值
                    console.log(newName);
                    let result;
                    for(let i = 0; i < newName.length; i++){
                        result += newName[i].name + ',' + newName[i].phone +';'
                        let end = result.slice(9);
                        this.contacts = end;
                        console.log(end)
                    }
                }
            }
        },
        computed: {
            
        },
        mounted(){
            console.log(this.type);
        },
        created(){
            // this.objid = 0;    //解决详细内容第一次不更新问题
            this.listSearchQuyu();  //查询并显示区域
            if(this.type=='add'){
                //清空输入框数据
                this.clearEntry();
                console.log('add++')
            }else{
                this.listDetail(this.objid);
            }
            
            console.log(this.type);
        }
    }
</script>

<style scoped>
    .oragin_info_form .title{
      font-size: 20px;
      margin-bottom: 10px;
    }
    .oragin_info_form .el-checkbox+.el-checkbox{
      margin-left: unset;
    }
    .oragin_info_form .el-icon-circle-plus-outline,.oragin_info_form .el-icon-circle-close-outline{
      font-size: 24px;
      vertical-align: middle;
      margin-left: 10px;
      color: #b3d3fb;
    }
    .fixed_button{
        position: fixed;
        bottom: 0px;
        margin-left: -20px;
        background: #e0eefd80;
        width: 50%;
        height: 60px;
        line-height: 60px;
        text-align: center;
    }
    .fixed_button .el-form-item{
            margin-top:10px;    
    }
    .el-dialog__header{
        border-bottom: 1px solid #ccc;
    }
</style>
